/**
 * @name Entry
 * @author darcrand
 * @desc
 */

import React, { Component } from 'react'
import { inject, observer } from 'mobx-react'

import { Avatar, Button } from '@/components'
import AvatarSelector from './AvatarSelector'
import Stardust from './stardust'
import styles from './styles.module.less'

@inject('UserStore')
@observer
class Entry extends Component {
  state = {
    info: { ...this.props.UserStore.info },
    avatarSelectorVisible: false
  }

  refContainer = React.createRef()

  componentDidMount() {
    new Stardust(this.refContainer.current)
    this.init()
  }

  init = async () => {
    try {
      const { isLogged, getInfo } = this.props.UserStore
      if (!isLogged) {
        const info = await getInfo()
        this.setState({ info })
      }
    } catch (err) {}
  }

  onInfoChange = data => {
    this.setState(prevState => ({ info: { ...prevState.info, ...data } }))
  }

  signIn = () => {
    const { name, avatar } = this.state.info
    this.props.UserStore.signIn({ name, avatar })
  }

  onUpdate = () => {
    const { name, avatar } = this.state.info
    this.props.UserStore.update({ name, avatar })
  }

  render() {
    const { info, avatarSelectorVisible } = this.state
    const { isLogged } = this.props.UserStore
    return (
      <div ref={this.refContainer} className={styles.container}>
        <div className={styles['content-box']}>
          <Avatar
            title="select your avatar"
            src={info.avatar}
            size="200px"
            style={{ margin: '0 auto', border: '5px solid #fff' }}
            onClick={() => this.setState({ avatarSelectorVisible: true })}
          />
          <input
            className={styles['name-input']}
            type="text"
            placeholder="nick name"
            maxLength={10}
            value={info.name}
            onChange={e => this.onInfoChange({ name: e.target.value })}
          />

          <div className={styles['button-bar']}>
            {isLogged && (
              <>
                <Button disable={!info.name} type="ghost" onClick={this.onUpdate}>
                  update
                </Button>
                <Button
                  type="ghost"
                  onClick={() => {
                    this.props.history.replace('/room')
                  }}
                >
                  chat now
                </Button>
              </>
            )}

            {!isLogged && (
              <Button disable={!info.name || !info.avatar} type="ghost" onClick={this.signIn}>
                sign up
              </Button>
            )}
          </div>
        </div>

        <AvatarSelector
          visible={avatarSelectorVisible}
          onCancel={() => this.setState({ avatarSelectorVisible: false })}
          onConfirm={src => {
            this.onInfoChange({ avatar: src })
            this.setState({ avatarSelectorVisible: false })
          }}
        />
      </div>
    )
  }
}

export default Entry
